package com.itheima.controller.servlet;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.service.RoleModuleService;
import com.itheima.service.impl.RoleModuleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/roleModuleServlet")
public class RoleModuleServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
    private RoleModuleService service = new RoleModuleServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        String method = request.getParameter("method");
        Map resultMap = null;
        if ("updateRoleModule".equals(method)){
            resultMap = this.updateRoleModule(request,response);
        }else if ("findRoleIdByModule".equals(method)){
            resultMap = this.findRoleIdByModule(request,response);
        }

        String json = objectMapper.writeValueAsString(resultMap);
        response.getWriter().write(json);
    }

    private Map findRoleIdByModule(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            String roleId = request.getParameter("roleId");
            List list = service.findRoleIdByModule(roleId);
            resultMap.put("flag",true);
            resultMap.put("resultData",list);
        } catch (Exception e) {
            resultMap.put("flag",false);
            resultMap.put("message","查询失败!");
            e.printStackTrace();
        }
        return resultMap;
    }

    private Map updateRoleModule(HttpServletRequest request, HttpServletResponse response) {
        Map resultMap = new HashMap();
        try {
            String roleId = request.getParameter("roleId");
            ServletInputStream is = request.getInputStream();
            List<String> list = objectMapper.readValue(is, new TypeReference<List<String>>() {});
            service.updateRoleModule(roleId,list);
            resultMap.put("flag",true);
        } catch (IOException e) {
            resultMap.put("flag",false);
            resultMap.put("message","修改失败!");
            e.printStackTrace();
        }
        return resultMap;
    }
}
